<template>
    <el-form ref="regForm" :model="form" :rules="rules" label-width="100px" class="registerForm sign-up-form">
        <el-tabs type="border-card" @tab-change="onChangeTab">
            <el-tab-pane label="个人用户">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名..."></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱..."></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" show-password placeholder="请输入密码...">

                    </el-input>
                    <!-- <div class="password-strength" style="width: 100px;height: 10px;" >
                        <div class="strength-bar" :style="{ backgroundColor: getStrengthColor(passwordStrength) }">
                            <div class="strength-level" :style="{ width: passwordStrength + '%' }"></div>
                        </div>
                    </div> -->
                </el-form-item>
                <el-form-item v-if="passwordStrength != 0">
                    <span>密码强度：</span>
                    <span v-if="0 < passwordStrength && passwordStrength < 7" style="color: red;">弱</span>
                    <span v-else-if="7 <= passwordStrength && passwordStrength < 10" style="color: orange;">中</span>
                    <span v-else-if="passwordStrength > 10" style="color: green;">强</span>
                </el-form-item>
                <el-form-item label="确认密码" prop="re_password">
                    <el-input v-model="form.re_password" type="password" show-password
                        placeholder="请输入确认密码..."></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" class="submit-btn" @click="register">注册
                    </el-button>
                </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="企业注册">

                <el-form-item label="是否管理员" prop="is_superuser">
                    <el-radio-group v-model="form.is_superuser" @change="setRegType">
                        <el-radio :label='true' size="large" border>是</el-radio>
                        <el-radio :label='false' size="large" border>否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名..."></el-input>
                </el-form-item>

                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱..."></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" show-password placeholder="请输入密码..."></el-input>
                </el-form-item>
                <el-form-item v-if="passwordStrength != 0">
                    <span>密码强度：</span>
                    <span v-if="0 < passwordStrength && passwordStrength < 7" style="color: red;">弱</span>
                    <span v-else-if="7 <= passwordStrength && passwordStrength < 10" style="color: orange;">中</span>
                    <span v-else-if="passwordStrength > 10" style="color: green;">强</span>
                </el-form-item>
                <el-form-item label="确认密码" prop="re_password">
                    <el-input v-model="form.re_password" type="password" show-password
                        placeholder="请输入确认密码..."></el-input>
                </el-form-item>


                <el-form-item label="企业名称" v-show="form.is_superuser === true" prop="company_name">
                    <el-input v-model="form.company_name" placeholder="输入企业名称"></el-input>
                </el-form-item>

                <el-form-item label="选择企业" v-show="form.is_superuser === false" prop="company">
                    <el-select placeholder="请输入所属企业..." v-model="form.company" style="width: 100%">
                        <el-option v-for="item in company_list" :key="item.id" :label="item.name"
                            :value="item.id"></el-option>
                    </el-select>
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" class="submit-btn" @click="register">注册
                    </el-button>
                </el-form-item>
            </el-tab-pane>
        </el-tabs>







    </el-form>



</template>

<script setup>
// vue 方法
import { reactive, ref, onMounted, watch } from "vue"
import { useRouter } from "vue-router"

// api
import { postRegister } from '~/api/user/login_register'
import { getCompanyList } from '~/api/company/index'

// 公共方法
import { toast } from "~/composables/util.js"


const router = useRouter();


const emit = defineEmits(['emitDialogVisibleRegister'])



// 初始化数据
const form = reactive({
    username: "",
    email: "",
    password: "",
    re_password: "",
    is_superuser: false,
    origin: 'web',
    company: '',
    company_name: "",
    reg_type: 0,  // 0 普通用户  1，公司员工，2，公司管理员
});

// 确认密码验证
const check_re_password = (rule, value, callback) => {
    if (value != form.password) {
        callback(new Error('两次密码不一致'))
    }
    callback()

}

const rules = reactive({
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在3-20之间', trigger: 'blur' },
    ],
    email: [
        { required: true, message: '请输入正确的邮箱', trigger: 'blur' },
        { type: "email", message: '请输入正确的邮箱', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '长度在6-20之间', trigger: 'blur' },
    ],
    re_password: [
        { required: true, message: '请输入确认密码', trigger: 'blur' },
        { validator: check_re_password, trigger: 'blur' },
    ],
    // company_name:[
    //     { required: true, message: '请输入确认公司名称', trigger: 'blur' },
    // ],
    // company:[
    //     { required: true, message: '请输入选择公司', trigger: 'blur' },
    // ]
})


const regForm = ref(null)

// 提交注册
const register = async () => {
    try {
        await regForm.value.validate((valid, field) => {
            if (!valid) {
                console.log("field", field)
                return false;
            }

            let postData = {
                username: form.username,
                email: form.email,
                password: form.password,
                re_password: form.re_password,
                is_superuser: form.is_superuser,
                origin: form.origin,
                reg_type: form.reg_type,
            };

            if (form.is_superuser === true) {
                postData.company_name = form.company_name;
            } else {
                postData.company = form.company;
            }

            postRegister(postData).then((res) => {
                toast("注册成功");
                emit('emitDialogVisibleRegister')
            }).catch((res) => {
            })

        })
    } catch (res) {
        toast("注册失败", 'error');
    }

};


// 密码强度：
const passwordStrength = ref(0)

watch(() => form.password, (newValue, oldValue) => {
    passwordStrength.value = newValue.length
});


const getStrengthColor = (strength) => {
      if (strength < 7) {
        return '#f00';
      } else if (strength < 10) {
        return '#ff0';
      } else {
        return '#0f0';
      }
    }

// tab触发事件
const onChangeTab = (tabname) => {
    if (tabname == '0') {
        form.reg_type = tabname
    } else {
        if (form.is_superuser) {
            form.reg_type = 2
        } else {
            form.reg_type = 1
        }
    }
}
// radio触发事件
const setRegType = (value) => {
    if (value) {
        form.reg_type = 2
    } else {
        loadComanyList()
        form.reg_type = 1
    }
}

// 加载
const company_list = ref([]);
const loadComanyList = () => {
    getCompanyList({})
        .then((res) => {
            company_list.value = res.data.results
        })
}
onMounted(() => {
    loadComanyList()
})



// 注册成功弹窗
const dialogVisibleRegister = ref(true)

const handleClose = () => {
    ElMessageBox.confirm('Are you sure to close this dialog?')
        .then(() => {
            done()
        })
        .catch(() => {
            // catch error
        })
}
</script>
<style scoped>
.password-strength {
  margin-top: 10px;
}
.strength-bar {
  height: 5px;
  width: 100%;
  background-color: #ddd;
  margin-top: 5px;
}
.strength-level {
  height: 100%;
  width: 0%;
  transition: width 0.5s ease;
}
</style>